<template>
  <div class="container">
    <el-dialog
      :title="addDialog.dialogType === 'edit' ? '修改调拨单' : '添加调拨单'"
      :visible.sync="addDialog.centerDialogVisible"
      @open="openData"
      @close="cancel"
      center
      width="99%"
    >
      <div class="top">
        <div style="margin-bottom: 5px">
          <el-select
            :multiple="false"
            filterable
            remote
            center
            reserve-keyword
            v-model="selectList"
            placeholder="选择调入配送中心"
            :remote-method="selectListsRemoteMethod"
            :loading="selectLists.loading"
          >
            <el-option
              v-for="item in selectLists.option"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>

        <el-select
          v-model="procurement.value"
          :multiple="false"
          filterable
          remote
          reserve-keyword
          placeholder="请选择调入采购员"
          :remote-method="insideProcurement"
          :loading="procurement.loading"
          @change="insidebuyer(procurement.value)"
        >
          <el-option
            v-for="item in procurement.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div style="margin-bottom: 5px">
        <el-switch
          v-model="is_sale"
          active-text="销售调拨单"
          inactive-text="普通调拨单"
        >
        </el-switch>
      </div>

      <div class="top">
        <el-select
          :multiple="false"
          filterable
          remote
          center
          reserve-keyword
          v-model="commodity"
          placeholder="商品编码/商品名称/仓库名称"
          :remote-method="insideRemoteMethod"
          :loading="inside.loading"
        >
          <el-option
            v-for="item in inside.option"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-search"
          @click="addGoods()"
          >添加</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="code"
          label="批次编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="erp_goods_code"
          label="商品编码"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="goods_name"
          label="商品名称"
          align="center"
        ></el-table-column>
        <!-- <el-table-column
          prop="category_name"
          label="品类名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="category_code"
          label="品类编码"
          align="center"
        ></el-table-column> -->
        <el-table-column
          prop="unit"
          label="商品单位"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="spec"
          label="商品规格"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="warehouse_code"
          label="调出仓库编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="warehouse_name"
          label="调出仓库名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="stock_net_num"
          label="库存剩余数量"
          align="center"
        ></el-table-column>
        <!-- <el-table-column
          prop="freeze_net_num"
          label="冻结数量"
          align="center"
        ></el-table-column> -->
        <el-table-column
          prop="stock_qty"
          label="剩余件数"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="inp_price"
          label="调拨成本 "
          align="center"
        ></el-table-column>
        <!-- 成本+加价 -->
        <el-table-column
          prop="goods_price"
          label="调拨单价"
          align="center"
        ></el-table-column>
        <el-table-column label="调拨数量" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              :max="scope.row.stock_net_num"
              size="small"
              :controls="false"
              v-model="scope.row.goods_num"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="调拨加价" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @blur="totalPrices(scope)"
              :controls="false"
              v-model="scope.row.markup"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="件数" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.qty"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label=" 调货提成" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.allocateprice"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="调货区域" align="center" width="160">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.allocateareaname"
              :multiple="false"
              filterable
              remote
              reserve-keyword
              placeholder="请选择调货区域编码/名称"
              :remote-method="insideArea"
              :loading="area.loading"
              @change="areabuyer(scope.row.allocateareaname, scope)"
            >
              <el-option
                v-for="item in area.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="调货来源采购员" align="center" width="160">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.allocatebuyer"
              :multiple="false"
              filterable
              remote
              reserve-keyword
              placeholder="请选择调货来源采购员"
              :remote-method="insideProcurements"
              :loading="allProcurement.loading"
              @change="allocatebuyer(scope.row.allocatebuyer, scope)"
            >
              <el-option
                v-for="item in allProcurement.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="danger"
              @click="remove(scope)"
              icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  selectAllocationBatchData,
  addAllocationInfo,
  findAllocationInfo,
  editAllocationInfo,
} from "@/api/allot/allotList";
import { getOrgAreaList } from "@/api/putStorage/putStotageList";
import { getToken } from "@/utils/auth";
import { Loading } from "element-ui";
import { selectRdcData } from "@/api/select/select";
import { getList } from "@/api/putStorage/putStotageList";
export default {
  props: {
    addDialog: Object,
  },
  data() {
    return {
      is_sale: false,
      tableData: [],
      goodsList: [],
      commodity: "",
      procurement: {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      },
      buyer: {
        name: "",
        code: "",
        id: "",
      },
      inside: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },
      selectLists: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },
      selectList: "",
      area: {
        options: [],
        list: [],
        loading: false,
      },
      allProcurement: {
        options: [],
        list: [],
        loading: false,
      },
    };
  },
  methods: {
    //取消
    cancel() {
      this.addDialog.centerDialogVisible = false;
      this.tableData = [];
      this.goodsList = [];
      this.commodity = "";
      this.procurement = {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      };
      this.buyer = {
        name: "",
        code: "",
        id: "",
      };
      this.inside = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      };
      this.selectLists = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      };
      this.area = {
        options: [],
        list: [],
        loading: false,
      };
      (this.allProcurement = {
        options: [],
        list: [],
        loading: false,
      }),
        (this.selectList = "");
    },
    getData() {
      if (this.addDialog.dialogType == "edit") {
        let data = {
          id: this.addDialog.id,
        };
        findAllocationInfo(data).then((res) => {
          if (res.code == 0) {
            this.selectList = res.data.info.inp_rdc_code;
            this.buyer.id = res.data.info.inp_buyer_id;
            this.buyer.code = res.data.info.inp_buyer_code;
            this.buyer.name = res.data.info.inp_buyer_name;
            this.procurement.value = res.data.info.inp_buyer_name;
            this.is_sale = res.data.info.is_sale ? true : false;
            res.data.goods.forEach((item) => {
              item.goods_bar_code = item.bar_code;
              item.code = item.batch_code;
              item.unit = item.goods_unit;
              item.spec = item.goods_spec;
              item.warehouse_code = item.out_house_code;
              item.warehouse_name = item.out_house_name;
              item.stock_net_num = parseFloat(item.stock_num);
              item.inp_price = item.goods_cost;
            });
            this.tableData = res.data.goods;
          }
        });
      }
    },
    //获取区域列表
    areaMent(query = "") {
      let data = {
        key: query,
      };
      this.area.loading = true;
      getOrgAreaList(data).then((res) => {
        this.area.options = res.data.map((item) => {
          return {
            value: `${item.code}`,
            label: `${item.name}/${item.code}`,
            name: `${item.name}`,
          };
        });
        this.area.loading = false;
      });
    },
    //搜索区域
    insideArea(query) {
      if (query !== "") {
        this.areaMent(query);
      } else {
        this.area.options = [];
      }
    },
    areabuyer(e, scope) {
      let center = this.area.options.filter((res) => {
        return res.value == e;
      });
      console.log(e, center);
      this.tableData[scope.$index].allocateareacode = center[0].value;
      this.tableData[scope.$index].allocateareaname = center[0].name;
    },
    getBatch(query = "") {
      let data = {
        keyword: query,
      };
      //获取批次
      selectAllocationBatchData(data).then((res) => {
        this.goodsList = res.data.list;
        this.inside.option = res.data.list.map((item) => {
          return {
            value: `${item.code}`,
            label: `${item.goods_name}(${item.code})`,
          };
        });
      });
    },
    // 调货采购员搜索
    allocatebuyer(e, scope) {
      let center = this.allProcurement.options.filter((res) => {
        return res.value == e;
      });
      console.log(e, center);
      this.tableData[scope.$index].allocatebuyer = center[0].name;
    },
    openData() {
      this.getselsetData();
      this.getBatch();
      this.purchase();
      this.getData();
      this.areaMent();
    },
    purchase() {
      let datas = {
        key: "",
      };
      //获取采购员
      getList(datas).then((res) => {
        this.procurement.options = res.data.map((item) => {
          return {
            value: `${item.code}`,
            label: `${item.name}(${item.code})`,
            id: `${item.id}`,
          };
        });
        this.allProcurement.options = res.data.map((item) => {
          return {
            value: `${item.code}`,
            label: `${item.name}(${item.code})`,
            name: `${item.name}`,
          };
        });
        this.procurementList = res.data;
      });
    },

    getselsetData(query = "") {
      let data = {
        page: 1,
        limit: 500,
        code_or_name: query,
      };
      //获取配送中心
      selectRdcData(data).then((res) => {
        if (res.data.paginate.data) {
          this.selectLists.option = res.data.paginate.data.map((item) => {
            return {
              value: `${item.d_code}`,
              label: `${item.d_name}`,
            };
          });
        }
      });
    },
    // 来源采购员
    getProcurements(query = "") {
      let data = {
        key: query,
      };
      this.procurement.loading = true;
      getList(data).then((res) => {
        this.allProcurement.options = res.data.map((item) => {
          return {
            value: `${item.code}`,
            label: `${item.name}(${item.code})`,
            name: `${item.name}`,
          };
        });
        this.allProcurement.loading = false;
      });
    },
    // 嵌套搜索配送方式数据
    selectListsRemoteMethod(query) {
      if (query !== "") {
        this.houseList(query);
      } else {
        this.selectLists.option = [];
      }
    },
    //获取配送数据
    houseList(query) {
      if (query !== "") {
        this.getselsetData(query);
      } else {
        this.procurement.options = [];
      }
    },
    //搜索来源采购员
    insideProcurements(query) {
      if (query !== "") {
        this.getProcurements(query);
      } else {
        this.allProcurement.options = [];
      }
    },
    //获取采购员name,code,id
    insidebuyer(e) {
      let center = this.procurementList.filter((res) => {
        return res.code == e;
      });
      console.log(center, 66666);
      this.buyer = {
        name: center[0].name,
        code: center[0].code,
        id: center[0].id,
      };
    },
    //搜索采购员
    insideProcurement(query) {
      if (query !== "") {
        this.getProcurement(query);
      } else {
        this.procurement.options = [];
      }
    },
    //获取采购员列表
    getProcurement(query) {
      let data = {
        key: query,
      };
      this.procurement.loading = true;
      getList(data).then((res) => {
        this.procurement.list = res.data.map((item) => {
          return {
            value: `${item.code}`,
            label: `${item.name}(${item.code})`,
            id: `${item.id}`,
          };
        });
        this.procurement.loading = false;
        this.procurement.options = this.procurement.list.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.procurementList = res.data;
      });
    },

    //删除
    remove(scope) {
      console.log(scope.row.code, 888);
      let code = scope.row.code;
      this.tableData.forEach((res, index) => {
        if (res.code == code) {
          this.tableData.splice(index, 1);
          console.log(this.tableData, 999);
        }
      });
      //   this.priceNum = 0;
    },
    // 添加商品
    addGoods() {
      if (this.commodity) {
        let every = this.tableData.filter((res) => {
          return res.code == this.commodity;
        });
        if (every.length == 0) {
          let arr = this.goodsList.filter((res) => {
            return res.code == this.commodity;
          });
          arr[0].goods_num = 0;
          arr[0].qty = 0;
          arr[0].allocateprice = 0;
          arr[0].allocateareacode = "";
          arr[0].allocateareaname = "";
          arr[0].allocatebuyer = "";
          arr[0].markup = 0;
          arr[0].batch_id = arr[0].id;
          arr[0].id = 0;
          arr[0].goods_price = arr[0].inp_price;
          arr[0].stock_net_num = parseFloat(arr[0].stock_net_num);
          this.tableData.push(arr[0]);
        } else {
          this.$message({
            type: "info",
            message: "该商品已添加",
          });
        }
      } else {
        this.$message({
          type: "info",
          message: "请选择商品",
        });
      }
    },

    // 获取批次方法
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getBatch(query);
      } else {
        this.inside.options = [];
      }
    },
    //修改调拨加价
    totalPrices(scope) {
      if (scope.row.markup != null || scope.row.markup != undefined) {
        scope.row.goods_price =
          parseFloat(scope.row.markup) + parseFloat(scope.row.inp_price);
      } else {
        scope.row.markup = 0;
        scope.row.goods_price =
          parseFloat(scope.row.markup) + parseFloat(scope.row.inp_price);
      }

      this.$set(this.tableData, scope.$index, scope.row);
    },
    //确定
    confirm() {
      if (this.buyer.code == "") {
        this.$message({
          type: "info",
          message: "请选择采购员",
        });
      } else if (this.selectList == "") {
        this.$message({
          type: "info",
          message: "请选择配送中心",
        });
      } else if (this.tableData.length == "") {
        this.$message({
          type: "info",
          message: "请添加批次",
        });
      } else {
        if (this.addDialog.dialogType == "edit") {
          let arr = [];
          this.tableData.forEach((res) => {
            arr.push({
              batch_id: res.batch_id,
              goods_num: res.goods_num,
              markup: res.markup,
              qty: res.qty,
              allocateprice: res.allocateprice,
              allocateareacode: res.allocateareacode,
              allocateareaname: res.allocateareaname,
              allocatebuyer: res.allocatebuyer,
              id: res.id,
            });
          });

          let data = {
            is_sale: this.is_sale ? 1 : 0,
            id: this.addDialog.id,
            inp_rdc_code: this.selectList,
            goods: JSON.stringify(arr),
            inp_buyer_id: this.buyer.id,
            inp_buyer_code: this.buyer.code,
            inp_buyer_name: this.buyer.name,
          };
          // console.log(data);
          // return;
          editAllocationInfo(data).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.msg || res.message,
              });
              this.$emit("upData");
              this.cancel();
            }
          });
        } else {
          let arr = [];
          this.tableData.forEach((res) => {
            arr.push({
              batch_id: res.batch_id,
              goods_num: res.goods_num,
              markup: res.markup,
              qty: res.qty,
              allocateprice: res.allocateprice,
              allocateareacode: res.allocateareacode,
              allocateareaname: res.allocateareaname,
              allocatebuyer: res.allocatebuyer,
              id: 0,
            });
          });

          let data = {
            is_sale: this.is_sale ? 1 : 0,
            inp_rdc_code: this.selectList,
            goods: JSON.stringify(arr),
            inp_buyer_id: this.buyer.id,
            inp_buyer_code: this.buyer.code,
            inp_buyer_name: this.buyer.name,
          };
          // console.log(data);
          // return;
          addAllocationInfo(data).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.msg || res.message,
              });
              this.$emit("upData");
              this.cancel();
            }
          });
        }
      }
    },
  },
};
</script>
<style scoped>
.pagination {
  text-align: right;
  padding: 10px;
}
.top {
  margin-bottom: 5px;
}
</style>
